import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../../../prisma/prisma.server';
import { create, update, getList, deleteDictCode } from './dict_data.dto';
import { nowDateTime } from '../../../utils/';
import { getUser } from '../../../utils/getUser';

@Injectable()
export class DictDataService {
  constructor(private readonly prisma: PrismaService) {}

  // 新增字典数据
  async create(
    {
      dictSort,
      dictType,
      dictValue,
      dictLabel,
      remark,
      status,
      listClass,
      cssClass,
      isDefault,
    }: create,
    token: string,
  ) {
    const user = await getUser(token);
    const currentTime = nowDateTime();
    return this.prisma.sysDictData.createMany({
      data: {
        dictLabel,
        dictType,
        dictValue,
        dictSort,
        remark,
        listClass,
        cssClass,
        isDefault,
        status: Boolean(status),
        createTime: currentTime,
        createBy: user,
      },
    });
  }

  // 修改字典数据
  async update(
    {
      dictSort,
      dictType,
      dictValue,
      dictLabel,
      remark,
      listClass,
      cssClass,
      dictCode,
      status,
    }: update,
    token: string,
  ) {
    const user = await getUser(token);
    const currentTime = nowDateTime();
    return this.prisma.sysDictData.updateMany({
      data: {
        dictLabel,
        dictType,
        dictValue,
        dictSort,
        remark,
        listClass,
        cssClass,
        status: Boolean(status),
        updateBy: user,
        updateTime: currentTime,
      },
      where: { dictCode },
    });
  }
  // 查询字典数据列表
  async getList({ pageSize, pageNum, dictType }: getList) {
    const skip = (pageNum - 1) * pageSize; // 计算跳过的记录数
    const [rows, total] = await Promise.all([
      this.prisma.sysDictData.findMany({
        where: { dictType },
        skip,
        take: pageSize,
        orderBy: { dictSort: 'asc' },
      }),
      this.prisma.sysDictData.count({ where: { dictType } }),
    ]);
    return { rows, total };
  }

  // 根据字典类型查询字典数据信息
  async getDictType(dictType: string) {
    return this.prisma.sysDictData.findMany({
      where: { dictType },
    });
  }

  // 查询字典数据详细
  async getDictCode(dictCode: string) {
    console.log(dictCode);
    return this.prisma.sysDictType.findFirst({ where: { dictId: +dictCode } });
  }

  // 删除字典数据
  async deleteDictCode({ dictCodes }: deleteDictCode) {
    {
      return this.prisma.sysDictData.deleteMany({
        where: { dictCode: { in: dictCodes } },
      });
    }
  }
}
